<script setup>
import { reactive, ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import CommonPagination from "@/components/pagination.vue";

// 导入订单相关接口（需要您实际创建这些API）
import { getOrderListApi, allocateOrderApi } from "@/service/order";
// 导入其他可能需要的API
import { getStatusPickerApi } from '@/service/setting';
import { getOpenedCityListApi } from '@/service/zone.js';
import { getCategoryListApi } from '@/service/goods.js';

// 引入订单相关组件
import OrderDetail from "./components/order-detail.vue";
import OrderAdd from "./components/order-add.vue";

// 分页配置
const pagination = reactive({
  page: 1,
  limit: 15,
  total: 0,
})

// 订单列表
const list = ref([]);

// 获取订单状态
const statusList = ref([]);
const fetchStatusList = () => {
  getStatusPickerApi().then(({code, data}) => {
    if (code === 200) {
      statusList.value = data;
    }
  });
};

// 获取分类
const categoryList = ref([]);
const fetchCategoryList = () => {
  getCategoryListApi().then(res => {
    if (res.code === 200) {
      categoryList.value = res.data.list;
    }
  });
};

// 获取开放的城市列表
const openedList = ref([]);
const fetchOpenedList = () => {
  getOpenedCityListApi().then(res => {
    if (res.code === 200) {
      openedList.value = res.data.list;
    }
  });
};

// 筛选条件
const filterForm = ref({
  order_no: '',
  status: '',
  category_id: '',
  city_id: '',
  date_range: [],
  payment_status: '',
  keyword: "",
});

// 获取订单列表
const fetchList = async () => {
  let params = {
    ...filterForm.value,
    pagination: pagination
  }
  // const { data } = await getOrderListApi(params);
  // list.value = data.list;
  // pagination.total = data.pagination.total;
};

// 搜索订单
const handleSearch = () => {
  pagination.page = 1;
  fetchList();
};

// 重置搜索条件
const handleReset = () => {
  filterForm.value = {
    order_no: '',
    status: '',
    category_id: '',
    city_id: '',
    date_range: [],
    payment_status: '',
    keyword: "",
  };
  pagination.page = 1;
  fetchList();
};

// 显示添加订单抽屉
const orderAddRef = ref(null);
const showAddOrder = () => {
  orderAddRef.value.openDrawer();
};

// 查看订单详情
const orderDetailRef = ref(null);
const showDetailDrawer = (row) => {
  orderDetailRef.value.openDrawer(row);
};

// 选择订单
const selectedList = ref([]);
const handleSelectionChange = (val) => {
  selectedList.value = val.map(item => item.id);
};

// 分配订单
import UserDialog from "@/pages/auth/user-dialog.vue";

const userDialogRef = ref(null);
const showAssignDialog = () => {
  if (selectedList.value.length === 0) {
    ElMessage.warning('请选择订单');
    return;
  }
  userDialogRef.value.openDialog();
};

// 执行订单分配
const handleAssign = (data) => {
  allocateOrderApi({
    order_ids: selectedList.value,
    user_id: data
  }).then(res => {
    if (res.code === 200) {
      ElMessage.success(res.msg);
      fetchList();
    } else {
      ElMessage.error(res.msg);
    }
  });
};

// 导出订单
const exportExcel = () => {
  console.log('导出订单');
}

// 支付状态选项
const paymentStatusOptions = [
  { label: '未支付', value: 'unpaid' },
  { label: '部分支付', value: 'partial' },
  { label: '已支付', value: 'paid' },
];

onMounted(() => {
  fetchStatusList();
  fetchCategoryList();
  fetchOpenedList();
  fetchList();
});
</script>

<template>
  <el-main>
    <div class="toolbar">
      <el-button type="danger" @click="showAddOrder">新增订单</el-button>
      
      <el-input v-model="filterForm.order_no" placeholder="订单号" clearable style="width: 120px"/>
      
      <el-select v-model="filterForm.status" placeholder="订单状态" clearable style="width: 120px">
        <el-option v-for="item in statusList" :key="item.id" :label="item.title" :value="item.id"/>
      </el-select>

      <el-select v-model="filterForm.category_id" placeholder="服务类型" clearable style="width: 120px">
        <el-option v-for="item in categoryList" :key="item.id" :label="item.title" :value="item.id"/>
      </el-select>

      <el-date-picker v-model="filterForm.date_range" type="daterange" range-separator="至"
                      start-placeholder="开始日期" end-placeholder="结束日期" style="max-width: 240px"
                      value-format="YYYY-MM-DD" format="YYYY-MM-DD" clearable/>
      
      <el-input v-model="filterForm.keyword" placeholder="客户/联系人" @keyup.enter="handleSearch" clearable
                style="max-width: 120px;"/>
      
      <el-button type="primary" icon="search" @click="handleSearch">搜索</el-button>
      <el-button type="danger" @click="handleReset">重置</el-button>
    </div>

    <el-table class="list" :data="list" row-key="id" border stripe style="width: 100%"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column prop="order_no" label="订单号" width="180"/>
      <el-table-column prop="user.realname" label="销售" width="100" align="center"/>
      <el-table-column prop="status.title" label="订单状态" width="100" align="center"/>
      <el-table-column prop="category.title" label="服务类型" align="center"/>
      <el-table-column prop="customer.name" label="客户姓名"/>
      <el-table-column prop="customer.contact" label="联系方式"/>
      <el-table-column prop="event_date" label="举办日期"/>
      <el-table-column prop="hall.title" label="宴会厅"/>
      <el-table-column prop="totals" label="订单金额" align="center" />
      <el-table-column prop="paid_amount" label="已支付" align="center">
        <template #default="{row}">
          ¥{{ row.paid_amount.toFixed(2) }}
        </template>
      </el-table-column>
      <el-table-column prop="create_time" label="创建时间" width="160"/>
    </el-table>

    <div class="pagination">
      <div class="btn-group">
        <el-button type="primary" @click="showAssignDialog">分配订单</el-button>
        
        <el-button type="warning" @click="exportExcel">导出</el-button>
      </div>
      
      <common-pagination :pagination="pagination" @fetch-list="fetchList"/>
    </div>
    
    <order-add ref="orderAddRef" @reload="fetchList"/>
    <order-detail ref="orderDetailRef" @reload="fetchList"/>
    <user-dialog ref="userDialogRef" @handleShare="handleAssign"/>
  </el-main>
</template>

<style scoped>
.toolbar {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.btn-group {
  display: flex;
  gap: 10px;
}
</style>